package com.plant.action;

import java.io.IOException;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.plant.entity.UgcFriends;
import com.plant.entity.UgcUser;
import com.plant.entity.UgcWeixinUserinf;
import com.plant.service.RegisterService;
import com.plant.tool.LoadJson;

@Controller
@RequestMapping(value="/webweixinlogin")
public class WebWeixinLogin {
	@Resource(name = "registerServiceImpl")  //spring 注入依赖管理 注入管理接口service
    private RegisterService registerService;
	
	
	@RequestMapping(value="access_token")
	@ResponseBody
	public Map<String, Object> GetAccessToken(HttpSession session,HttpServletResponse response,UgcWeixinUserinf uwf,HttpServletRequest request,UgcUser user){//微信公众号获取 ACCESSToken
		Map<String, Object> map=new HashMap<String, Object>();
		String code=request.getParameter("code");
		String redirect_uri=request.getParameter("redirect_uri");
		System.out.println(code);
		String appid="wx03ccc79e3652fd7c";
		String secret="8618798bea2e36b15979fb227077ad93";
		String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
		String json=LoadJson.loadJson(url);
		try {
			JSONTokener jsonParser=new JSONTokener(json);
			JSONObject getaccess=(JSONObject)jsonParser.nextValue();
			if(!getaccess.has("access_token")){
				getaccess.put("access_token", "");
			}
			String AccessToken=getaccess.getString("access_token");
			if(AccessToken!=null){
				String openid=getaccess.getString("openid");
				System.out.println("openid"+openid);
				String userinfurl="https://api.weixin.qq.com/sns/userinfo?access_token="+AccessToken+"&openid="+openid+"&lang=zh_CN ";
				String stringuserinf=LoadJson.loadJson(userinfurl);
				JSONTokener jsonuserinf=new JSONTokener(stringuserinf);
				JSONObject jsonobjuser=(JSONObject)jsonuserinf.nextValue();
				System.out.println("微信opeonid"+jsonobjuser.getString("openid")+"用户姓名"+jsonobjuser.getString("nickname"));
				String nickname=jsonobjuser.getString("nickname");
				String sex=jsonobjuser.getString("sex");
				String province=jsonobjuser.getString("province");
				String city=jsonobjuser.getString("city");
				String country=jsonobjuser.getString("country");
				String headimgurl=jsonobjuser.getString("headimgurl");
				String unionid=jsonobjuser.getString("unionid");
				if(nickname!=null){
		    	   user.setWeixinUnionId(unionid);
 				   user.setWeixinOpenId(openid);
 				   UgcUser u=registerService.CheckUnionId(user);
		    		   if(u!=null){//-----根据用户手机的UNIONID判断   如果是新用户就变成我们的用户  如果是老用户直接微信登录
		    			    u.setWeixinUnionId(unionid);
		    			    registerService.UpdatePass(u);
		    			    try {
		    			    	session.setAttribute("nickname", u.getNickname());
		    			    	Cookie idcookie=new Cookie("user_id",String.valueOf(u.getId()));
		    			    	Cookie nicknamecookie=new Cookie("user_nickname",URLEncoder.encode(nickname, "utf-8")); 
 		    			    	Cookie photocookie=new Cookie("photo",URLEncoder.encode(u.getPhoto(), "utf-8")); 
		    			    	idcookie.setPath("/");
		    			    	photocookie.setPath("/");
		    			    	nicknamecookie.setPath("/");
		    			    	response.addCookie(idcookie);
		    			    	response.addCookie(nicknamecookie);
		    			    	response.addCookie(photocookie);
								response.sendRedirect(redirect_uri+"#showinput");
								response.setCharacterEncoding("utf8");
							} catch (IOException e) {
								e.printStackTrace();
							}
		    		   }else{
		    			   SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		    			   String t=sim.format(new Date());
		    			   GetIp getip=new GetIp();
		    			   String ip=getip.getIp2(request);
		    			   uwf.setOpenId(openid);
		    			   uwf.setUnionId(unionid);
		    			   uwf.setCity(city);
		    			   uwf.setCountry(country);
		    			   uwf.setHeadimgurl(headimgurl);
		    			   uwf.setProvince(province);
		    			   uwf.setLanguage("zh_CN");
		    			   registerService.AddWeiXinUser(uwf);
		    			   user.setNickname(nickname);
		    			   if(sex.endsWith("1")){
		    				   user.setSex("男");
		    			   }else{
		    				   user.setSex("女");
		    			   }
		    			   int radomInt = new Random().nextInt(999999);//----随机产生6位数随机数
	        			   user.setMyId("ID:"+radomInt);
		    			   user.setPhoto(headimgurl);
		    			   user.setWeixinOpenId(openid);
		    			   user.setRegisterTime(Timestamp.valueOf(t));
		    			   user.setIp(ip);
		    			   user.setWeixinUnionId(unionid);
		    			   boolean b=registerService.addtel(user);
		    			   if(b){
		    				    List<Object> list2=new ArrayList<Object>();
	        					list2=registerService.GetByOpenId(user);
	        					UgcUser uu=null;
	        					for (int i = 0; i < list2.size(); i++) {
									uu=(UgcUser) list2.get(0);
								}
	        					int[] ids={149,150,151,152,153,154,35};
	        					for (int i = 0; i <ids.length; i++) {
	        						UgcFriends uf=new UgcFriends();
	        						uf.setReceiveUserId(uu.getId());
	        						uf.setApplyUserId(ids[i]);
	        						uf.setCreateTime(Timestamp.valueOf(t));
	        						uf.setIp(ip);
	        						registerService.addfriend(uf);
								}
	        					 try {
	 		    			    	session.setAttribute("nickname", user.getNickname());
	 		    			    	Cookie idcookie=new Cookie("user_id",String.valueOf(user.getId())); 
	 		    			    	Cookie nicknamecookie=new Cookie("user_nickname",URLEncoder.encode(user.getNickname(), "utf-8")); 
	 		    			    	Cookie photocookie=new Cookie("photo",URLEncoder.encode(user.getPhoto(), "utf-8")); 
	 		    			    	idcookie.setPath("/");
	 		    			    	nicknamecookie.setPath("/");
	 		    			    	photocookie.setPath("/");
	 		    			    	response.addCookie(idcookie);
	 		    			    	response.addCookie(nicknamecookie);
	 		    			    	response.addCookie(photocookie);
	 								response.sendRedirect(redirect_uri+"#showinput");
	 							} catch (IOException e) {
	 								e.printStackTrace();
	 							}
		    			   }else{
		    				   map.put("message", "登录失败");
		    				   map.put("state", 0);
		    			   }
		    		   }
		    		   return map;
					}
				}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return map;
	}
	
}
